package chapter6_2_condition;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Summerday
 */
public class ReentrantLockDemo {

    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {

        Thread A = new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "拿到锁了");
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName() + "释放锁了");
            }
        },"A");

        Thread B = new Thread(() -> {
            if(!lock.tryLock()){
                System.out.println(Thread.currentThread().getName() + "想尝试获取锁,但是失败了,直接返回了");
            }else{
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "拿到锁了");
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                    System.out.println(Thread.currentThread().getName() + "释放锁了");
                }
            }
        },"B");

        long start = System.currentTimeMillis();
        A.start();
        Thread.sleep(100);
        B.start();
        A.join();
        B.join();

        System.out.println("spend : " + (System.currentTimeMillis() - start) / 1000 + "s.");

    }

}
